package com.pktechan.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pktechan.api.entity.CustAddress;
import com.pktechan.api.entity.CustBase;
import com.pktechan.api.exception.CustomException;
import com.pktechan.api.service.CustAddressService;
import com.pktechan.api.service.CustBaseService;
import com.pktechan.api.service.RedisService;
import com.pktechan.api.utils.FastDfsHttpUtil;
import com.pktechan.api.utils.FileResponseData;
import com.pktechan.api.utils.HtmlUtil;
import com.pktechan.api.utils.StringUtil;
import com.pktechan.api.vo.ReferencesVO;
import com.pktechan.api.vo.SalesCenterVO;
import com.pktechan.api.vo.TradeOrderVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * @program: cloudfloating
 * @description: 产品相关功能
 * @author: qx.zhang
 * @create: 2021-03-05 11:27
 **/
@RestController
@RequestMapping("custBaseController")
public class CustBaseController {

    private static final Logger logger = LoggerFactory.getLogger(CustBaseController.class);

    @Autowired
    private CustBaseService custBaseService;

    @Autowired
    private CustAddressService custAddressService;
    @Autowired
    private RedisService redisService;

    @RequestMapping("getCustBaseById")
    public void getCustBaseById(Integer id, HttpServletResponse response) {
        try {
            CustBase custBase = custBaseService.getById(id);
            HtmlUtil.writerSuccessJson(response, custBase);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }


    @RequestMapping("saveCustBase")
    public void saveCustBase(CustBase custBase, HttpServletResponse response) {
        try {
            logger.info("添加客户信息");
            custBaseService.save(custBase);
            //客户信息有修改，查询最新客户基本信息，将客户基本信息保存到redis中。
            custBase = custBaseService.getById(custBase.getId());
            redisService.setCustBaseByOpenId(custBase.getOpenId(), JSONObject.toJSONString(custBase));
            HtmlUtil.writerSuccessJson(response);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    @RequestMapping("updateCustBase")
    public void updateCustBase(CustBase custBase, HttpServletResponse response) {
        try {
            logger.info("修改到客户信息 id= " + custBase.getId());
            custBaseService.update(custBase);
            //客户信息有修改，查询最新客户基本信息，将客户基本信息保存到redis中。
            custBase = custBaseService.getById(custBase.getId());
            redisService.setCustBaseByOpenId(custBase.getOpenId(), JSONObject.toJSONString(custBase));
            HtmlUtil.writerSuccessJson(response);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    @RequestMapping("updateNickNameAvatar")
    public void updateNickNameAvatar(@RequestBody CustBase custBaseT, HttpServletResponse response) {
        try {
            logger.info("修改头像昵称 id= " + custBaseT.getId());
            CustBase custBase = custBaseService.getById(custBaseT.getId());
            custBase.setNickname(custBaseT.getNickname());
            custBase.setHeadImgUrl(custBaseT.getHeadImgUrl());
//            FileResponseData fileResponseData = FastDfsHttpUtil.uploadFile(custBaseT.getHeadImgUrl(), custBaseT.getNickname());
//            custBase.setHeadImgUrl(fileResponseData.getHttpUrl());
            custBaseService.update(custBase);
            //客户信息有修改，查询最新客户基本信息，将客户基本信息保存到redis中。
            custBase = custBaseService.getById(custBase.getId());
            redisService.setCustBaseByOpenId(custBase.getOpenId(), JSONObject.toJSONString(custBase));
            HtmlUtil.writerSuccessJson(response);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 保存客户头像至FastDFS
     */
    /**
     * 修改产品信息

     * @param response
     */
    @RequestMapping(value = "savaAvatarUrl", method = RequestMethod.POST)
    public void savaAvatarUrl(@RequestParam String nickName, @RequestParam(required = false, value = "avatarUrl") MultipartFile avatarUrl, HttpServletResponse response) {
        try {
            logger.info("上传FastDFS用户头像 nicker = "+ nickName);
            FileResponseData fileResponseData = FastDfsHttpUtil.uploadFile(avatarUrl, nickName);
//          productBaseInfo.setThumbImagePath(fileResponseData.getFilePath());
//          productBaseInfo.setThumbImageUrl(fileResponseData.getHttpUrl());
            HtmlUtil.writerSuccessJson(response, fileResponseData.getHttpUrl());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @param response
     */
    @RequestMapping(value = "getCustAddressById", method = RequestMethod.POST)
    public void getCustAddressById(@RequestParam Integer id, HttpServletResponse response) {
        try {
            logger.info("根据id=" + id + "查询地址");
            CustAddress custAddress = custAddressService.getById(id);
            HtmlUtil.writerSuccessJson(response, custAddress);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 地址列表
     *
     * @param custAddress
     * @param response
     */
    @RequestMapping(value = "getCustAddressList", method = RequestMethod.POST)
    public void getProductChannelFeeList(@RequestBody CustAddress custAddress, HttpServletResponse response) {
        try {
            logger.info("地址列表");
            PageHelper.startPage(custAddress.getPageNo(), custAddress.getPageSize());
            List<CustAddress> list = custAddressService.getList(custAddress);
            PageInfo pageInfo = new PageInfo(list);
            HtmlUtil.writerSuccessJson(response, pageInfo);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 添加到客户地址
     *
     * @param custAddress
     * @param response
     */
    @RequestMapping(value = "saveCustAddress", method = RequestMethod.POST)
    public void saveCustAddress(@RequestBody CustAddress custAddress, HttpServletResponse response) {
        try {
            logger.info("添加到客户地址");
            custAddressService.save(custAddress);
            HtmlUtil.writerSuccessJson(response);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 根据Id修改客户地址
     *
     * @param custAddress
     * @param response
     */
    @RequestMapping(value = "updateCustAddressById", method = RequestMethod.POST)
    public void updateCustAddressById(@RequestBody CustAddress custAddress, HttpServletResponse response) {
        try {
            logger.info("根据id=" + custAddress.getId() + "修改地址信息表");
            custAddressService.update(custAddress);
            HtmlUtil.writerSuccessJson(response);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 根据Id删除地址信息表
     *
     * @param id
     * @param response
     */
    @RequestMapping(value = "deleteShopCartById", method = RequestMethod.POST)
    public void deleteShopCartById(@RequestParam Integer id, HttpServletResponse response) {
        try {
            logger.info("根据id=" + id + "删除地址信息表");
            custAddressService.deleteById(id);
            HtmlUtil.writerSuccessJson(response);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 客户注册
     *
     * @param response
     */
    @RequestMapping(value = "registration", method = RequestMethod.POST)
    public void registration(@RequestParam String headImgUrl,@RequestParam String nickName,@RequestParam String mobile, @RequestParam Integer bbId, @RequestParam String code, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("客户注册");
            CustBase custBase = redisService.getCustBaseByUserLoginState(request.getParameter("userLoginState"));
            custBase.setMobile(mobile);
            custBase.setBbId(bbId);
            custBase.setHeadImgUrl(headImgUrl);
            custBase.setNickname(nickName);
            custBaseService.registration(custBase, code);
            HtmlUtil.writerSuccessJson(response, custBase);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 销售中心
     *
     * @param custId
     * @param response
     */
    @RequestMapping(value = "/getSalesCenterDetail", method = RequestMethod.POST)
    public void getSalesCenterDetail(@RequestParam Integer custId, HttpServletResponse response) {
        try {
            logger.info("销售中心");
            SalesCenterVO salesCenterVO = custBaseService.getSalesCenterDetail(custId);
            HtmlUtil.writerSuccessJson(response, salesCenterVO);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 根据userLoginState获取当前客户
     *
     * @param response
     */
    @RequestMapping(value = "/getCustBaseByUserLoginState", method = RequestMethod.POST)
    public void getCustBaseByUserLoginState(@RequestParam String userLoginState, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("根据userLoginState=" + userLoginState + "获取当前客户");
            CustBase custBase = custBaseService.getCustBaseByUserLoginState(userLoginState);
            HtmlUtil.writerSuccessJson(response, custBase);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 获取直接推荐人信息
     *
     * @param response
     */
    @RequestMapping(value = "/getDirectReferencesDetail", method = RequestMethod.POST)
    public void getDirectReferencesDetail(@RequestParam Integer custId, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.warn("根据custId=" + custId + "获取当前客户");
            List<ReferencesVO> referencesVOS = custBaseService.getDirectReferencesDetail(custId);
            HtmlUtil.writerSuccessJson(response, referencesVOS);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

    /**
     * 实名认证
     *
     * @param response
     */
    @RequestMapping(value = "realNameAuth", method = RequestMethod.POST)
    public void realNameAuth(@RequestParam String idCard, @RequestParam String name, @RequestParam String imageCode, HttpServletRequest request, HttpServletResponse response) {
        try {
            String userLoginState = request.getParameter("userLoginState");
            logger.info("客户实名认证");
            CustBase custBase = redisService.getCustBaseByUserLoginState(userLoginState);
            //验证图片验证码
            String realNameImageCode = redisService.getRealNameImageAuthCode(userLoginState);
            if (!StringUtil.equals(realNameImageCode, imageCode)) {
                throw new CustomException("图片验证码错误");
            }
            custBase.setCertCode(idCard);
            custBase.setName(name);
            custBaseService.realNameAuth(custBase, imageCode);
            HtmlUtil.writerSuccessJson(response, custBase);
        } catch (CustomException e) {
            e.printStackTrace();
            logger.debug(e.getErrMsg());
            HtmlUtil.writerFailJson(response, e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e.getMessage());
            HtmlUtil.writerFailJson(response, e.getMessage());
        }
    }

}
